// pages/newplay/newplay.js
var util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: '',
    date: '',
    action: {
      method: "play"
    },
    state: 'play',
    mode: 'loop',
    isTogether: false,
    imgSrc: '',
    audioSrc: '',
    songID: '',
    songIDs: [],
    songName: '',
    songNames: [],
    lyricArray: [],
    marginTop: 0,
    currentIndex: 0,
    scrollAnimation: true,
    playTime: '00:00',
    endTime: '00:00',
    max: 100,
    move: 0
  },

  //获取实时时间
  getTime() {
    var time = util.formatTime1(new Date());
    var date = util.formatDate(new Date());
    this.setData({
      time: time,
      date: date
    })
  },

  //播放模式
  changeMode() {
    var mode = this.data.mode;
    if(mode == 'single') {
      this.setData({
        mode: 'loop'
      })
    } else if(mode == 'loop') {
      this.setData({
        mode: 'single'
      })
    }
  },

  //单曲&列表
  changeMusic() {
    var mode = this.data.mode;
    if(mode == 'single') {
      this.switchPlay();
    } else if(mode == 'loop') {
      this.nextSong();
    }
  },

  // 播放&暂停
  isPlay() {
    var state = this.data.state;
    if(state == 'play') {
      this.setData({
        action: {
          method: 'pause'
        },
        state: 'pause'
      })
    } else {
      this.setData({
        action: {
          method: 'play'
        },
        state: 'play'
      })
    }
  },

  //切换播放
  switchPlay() {
    this.setData({
      action: {
        method: 'play'
      },
      state: 'play',
      marginTop: 0,
      currentIndex: 0
    })
  },

  //上一首歌曲
  prevSong() {
    var currentID = this.data.songID;
    var index = 0;
    for(var i=0; i<this.data.songIDs.length; i++) {
      if(currentID == this.data.songIDs[i]) {
        index = i;
        break;
      }
    }
    var prevIndex = index==0 ? this.data.songIDs.length-1 : index-1;
    var prevID = this.data.songIDs[prevIndex];
    var prevName = this.data.songNames[prevIndex];
    this.setData({
      songID: prevID,
      songName: prevName
    })
    this.getSong({name: this.data.songName, names: this.data.songNames.join(), id: this.data.songID, ids: this.data.songIDs.join()});
    this.getLyric(this.data.songID);
    this.switchPlay();
  },

  //下一首歌曲
  nextSong() {
    var currentID = this.data.songID;
    var index = 0;
    for(var i=0; i<this.data.songIDs.length; i++) {
      if(currentID == this.data.songIDs[i]) {
        index = i;
        break;
      }
    }
    var nextIndex = index==this.data.songIDs.length-1 ? 0 : index+1;
    var nextID = this.data.songIDs[nextIndex];
    var nextName = this.data.songNames[nextIndex];
    this.setData({
      songID: nextID,
      songName: nextName
    })
    this.getSong({name: this.data.songName, names: this.data.songNames.join(), id: this.data.songID, ids: this.data.songIDs.join()});
    this.getLyric(this.data.songID);
    this.switchPlay();
  },

  //获取歌曲信息
  getSong(options) {
    var id = options.id;
    var ids = options.ids.split(",");
    var name = options.name;
    var names = options.names.split(",");
    this.setData({
      audioSrc: 'http://49.233.35.127/Wx/Getvideo/?id='+id,
      songID: id,
      songIDs: ids,
      songName: name,
      songNames: names
    });
  },

  //获取歌词信息
  getLyric(id) {
    var id = id;
    var that = this;
    wx.request({
      url: 'http://49.233.35.127/Wx/Getlrc/?id='+id,
      success: function(res) {
        if(res.data != '') {
          var lyric = res.data;
          var result = that.parseLyric(lyric);
          var realResult = that.sliceNull(result);
          that.setData({
            lyricArray: realResult
          })
        }
      }
    })
  },

  //解析歌词
  parseLyric(lyric) {
    var lyricArray = lyric.split('\n');
    if(lyricArray[lyricArray.length-1] == '') {
      lyricArray.pop();
    }
    var pattern = /\[\d{2}:\d{2}\.\d{2,3}\]/;
    var lyricResult = [];
    lyricArray.forEach(function(item,i,a) {
      var realLyric = item.replace(pattern, '');
      var lyricTime = item.match(pattern);
      if(lyricTime != null) {
        var realTime = lyricTime[0].slice(1,-1);
        var timeArray = realTime.split(':');
        var finalTime = parseFloat(timeArray[0])*60 + parseFloat(timeArray[1]);
        lyricResult.push([finalTime, realLyric]);
      }
    })
    return lyricResult;
  },

  //去除空歌词（可用可不用）
  sliceNull(lyricArray) {
    var result = [];
    for(var i=0; i<lyricArray.length; i++) {
      if(lyricArray[i][1] != '') {
        result.push(lyricArray[i]);
      }
    }
    return result;
  },

  //进度条时间&歌词滚动
  changeTime(e) {
    //进度条时间
    var currentTime = e.detail.currentTime;
    var duration = e.detail.duration;
    var playMinutes = Math.floor(currentTime/60);
    var playSeconds = Math.floor(currentTime%60);
    var endMinutes = Math.floor(duration/60);
    var endSeconds = Math.floor(duration%60);
    if(playMinutes < 10) {
      playMinutes = '0'+playMinutes;
    }
    if(playSeconds < 10) {
      playSeconds = '0'+playSeconds;
    }
    if(endMinutes < 10) {
      endMinutes = '0'+endMinutes;
    }
    if(endSeconds < 10) {
      endSeconds = '0'+endSeconds;
    }
    this.setData({
      playTime: playMinutes+':'+playSeconds,
      endTime: endMinutes+':'+endSeconds,
      max: duration,
      move: currentTime
    })
    
    //歌词滚动
    var lyricArray = this.data.lyricArray;
    if(this.data.currentIndex >= 2) {
      this.setData({
        marginTop: (this.data.currentIndex-2)*40
      })
    }
    if(this.data.currentIndex == lyricArray.length-6) {
      this.setData({
        scrollAnimation: false
      })
    }
    if(this.data.currentIndex == lyricArray.length-2) {
      if(currentTime>=lyricArray[lyricArray.length-1][0]) {
        this.setData({
          currentIndex: lyricArray.length-1
        })
      }
    } else {
      for(var i=0; i< lyricArray.length-1; i++) {
        if(currentTime>=lyricArray[i][0] && currentTime<lyricArray[i+1][0]) {
          this.setData({
            currentIndex: i
          })
        }
      }
    }
  },

  //拖动进度条改变歌曲进度
  progressChange(e) {
    var value = e.detail.value;
    // this.audioCtx.seek(value);
    this.setData({
      move: value,
      action: {
        method: 'setCurrentTime',
        data: value
      }
    });
  },
  
  // 发送请求（启动一起听）
  share() {
    wx.request({
      url: 'url',
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      data: {
        'userName': '',
        'userImg': '',
        'songID': this.data.songID
      },
      success: (res) => {
        this.setData({
          imgSrc: '',
          action: {
            method: 'setCurrentTime',
            data: 0
          }
        })
        wx.hideLoading()
      }
    })
  },

  // 一起听
  isTogether() {
    if(this.data.isTogether == false) {
      this.setData({
        isTogether: true
      });
      wx.showLoading({
        title: '正在为您匹配中'
      });
      this.share();
    } else {
      this.setData({
        isTogether: false
      })
      wx.hideLoading()
    }
  },

  //对话框
  showTalk() {
    wx.showModal({
      title: '1',
      content: '1',
      confirmText: '发送',
      editable: true,
      placeholderText: '你可以和新朋友一起交流啦！',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getSong(options);
    this.getLyric(options.id);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.audioCtx = wx.createAudioContext('myAudio');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getTime();
    setInterval(this.getTime,60000);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})